<script>
import TreeTableContainerList from '@/mixins/treeTableContainerList'
import AjaxStore from '@/utils/store/proxyAjax'

export default {
  name: 'managerFenpei',
  inject: ['Dialog'],
  props: {
    projectId: Number
  },
  mixins: [TreeTableContainerList],
  data() {
    return {
      isShowTitle: false,

      tree: {
        width: '280',
        height: '200',
        accordion: false,
        isShowHeader: false,
        treeMenuButtonList: [],
        treeOperateButtonList: [],
        showCheckbox: false,
        selectTree: {
          disabled: true,
          treeParams: {
            get: {
              url: '/v1/dataProvider/getGroupTreeList',
              idKey: 'id',
              nextNodeKey: 'pid'
            }
          },
          valueToLabelParams: {
            url: '/v1/dataProvider/getGroupName',
            idKey: 'groupId'
          },
          clearable: true,
          selectCodeVal: this.$store.getters.groupId || '',
          selectCodeKey: 'groupId'
        },
        emptyTopNode: {
          expanded: true,
          id: '',
          leaf: false,
          text: '部门树'
        },
        nextNodeKey: 'node',
        idKey: 'deptId',
        search: {
          searchKey: 'deptName'
        },
        title: '',
        getNextChildNode: this.getNextNode,
        delNode: this.delNode
      },
      pidKey: 'pid',
      nodeCheckedKey: 'checked',
      nodeChildrenKey: 'children',
      nodeLeafKey: 'leaf',
      nodeIdKey: 'id',
      nodeLabelKey: 'text',

      currentNode: null,
      dialogType: '',

      // table
      inputPlaceholder: '输入账号或姓名搜索',
      tableUniqueId: 'userId',

      // containerList
      containerListTitle: '已分配人员',
      titleKey: '当前站点',
      titleValue: '',

      // table
      groupId: '',
      selectedList: [],
      containerList: [],
      currentTentKey: '当前站点',
      currentTentName: '',
      idKey: 'deptId',
      allPath: '',
      getAllPathUrl: '/v1/yq/common/getAllPath',
      getNextNodeUrl: '/v1/dataProvider/getDeptmentTreeList',
      getNodeInfoUrl: '/v1/sys/deptment/findById',
      store: new AjaxStore({
        url: `/v1/sys/role/getUserListByDeptId?projectId=${this.projectId}`
      }),
      columns: [
        {
          prop: 'userNo',
          label: '账号',
          sortable: true,
          'show-overflow-tooltip': true,
          'header-align': 'center'
        },
        {
          prop: 'userName',
          label: '姓名',
          sortable: true,
          'show-overflow-tooltip': false,
          'header-align': 'center',
          scopedSlots: {
            default: scope => {
              return (
                <c-popover
                  trigger='hover'
                  ref='popover'
                  on-show={this.getUserAllPath.bind(
                    this,
                    scope.row.userId,
                    scope.row.userName
                  )}
                  placement='top'
                  popper-class={this.setClassName(scope.row.userId)}>
                  {this.allPath}
                  <div slot='reference' class='name-wrapper user-name'>
                    {scope.row.userName}
                  </div>
                </c-popover>
              )
            }
          }
        },
        {
          prop: 'deptName',
          label: '部门',
          sortable: true,
          'show-overflow-tooltip': true,
          'header-align': 'center'
        },
        {
          prop: 'dataStatus',
          label: '状态',
          sortable: true,
          width: '100',
          'header-align': 'center',
          formatter: (row, column, cellValue) => (cellValue ? '启用' : '停用')
        }
      ]
    }
  },
  watch: {
    'Dialog.visible': {
      immediate: true,
      handler(val) {
        val && this._getFenpeiUserInfo()
        val &&
          this.$nextTick(() => {
            this.$refs.tree.load()
          })
      }
    },
    data: {
      // immediate: true,
      handler() {
        this.handleCheckCheckbox()
      }
    }
  },
  methods: {
    setClassName(userId) {
      return `el-tooltip__popper is-dark username-popover username-${userId}-popover`
    },
    getUserAllPath(id, userName) {
      return this.request({
        url: this.getAllPathUrl,
        method: 'get',
        params: { userId: id }
      })
        .then(({ success, message }) => {
          if (success) {
            this.$nextTick(() => {
              const popover = document.getElementsByClassName(
                `username-${id}-popover`
              )[0]
              popover.classList.remove('el-popover')
              popover.classList.remove('el-popper')
            })
            const changePath = message.replace(/\//g, '\\')
            this.allPath = changePath
          } else {
            this.allPath = userName
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    handleTreeSubSelect(val) {
      val && (this.groupId = val)
      !val && (this.groupId = '')
    },
    _getFenpeiUserInfo() {
      return new Promise((resolve, reject) => {
        return this.request({
          url: '/v1/yq/project/findUsersById',
          method: 'post',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          data: { projectId: this.projectId }
        })
          .then(({ success, data }) => {
            if (success) {
              this.containerList = data
              this.handleCheckCheckbox()
              resolve(data)
            } else {
              this.$message({
                type: 'error',
                message: '获取已分配站点管理人员信息失败！'
              })
              reject(new Error('获取已分配站点管理人员信息失败！'))
            }
          })
          .catch(err => {
            console.log(err)
            reject(err)
          })
      })
    },
    handleInputClick(ev, val) {
      const params = {}
      if (this.$refs.tree.currentNode) {
        params.q_deptId = this.$refs.tree.currentNode.key
        params.q_name = val
        this.store._searchParams = params
        this.$refs.table.load(1, this.store.limit)
      }
    },
    handleTreeEmpty() {
      const params = {}
      params.q_deptId = -1
      params.q_name = ''
      this.store._searchParams = params
      this.$refs.table.load(1, this.store.limit)
    },
    formaterTagContent(item) {
      return item.userName + '-' + item.userNo
    }
  }
}
</script>

<style lang="scss">
.username-popover {
  .popper__arrow {
    display: none;
  }
}
</style>
